package com.lebang.controller.sys;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lebang.common.Login;
import com.lebang.configuration.datasource.DataSource;
import com.lebang.domain.TaskRouse;
import com.lebang.domain.TaskRouseDetail;
import com.lebang.domain.TaskWorthDetail;
import com.lebang.domain.TaskWorthRecord;
import com.lebang.entity.sys.LbbUser;
import com.lebang.entity.task.TaskScreenshot;
import com.lebang.example.TaskWorthRecordExample;
import com.lebang.mapper.LbbUserMapper;
import com.lebang.model.MyConfig;
import com.lebang.service.NewRouseService;
import com.lebang.service.TaskRouseDetailService;
import com.lebang.service.TaskWorthRecordService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 任务价值录制
 *
 * @author xwj
 * @date 2020-09-18
 */
@Controller
@RequestMapping("/sys/taskworthrecord")
public class TaskWorthRecordController {
    @Autowired
    private TaskWorthRecordService baseService;
    @Autowired
    private NewRouseService newRouseService;
    @Autowired
    private LbbUserMapper lbbUserMapper;
    @Value("#{'${check.sdkList}'.split(',')}")
    private List<String> sdkList;

    @Login
    @GetMapping("/list")
    public String list(Model model, HttpSession session) {
        List<TaskRouse> rouses = newRouseService.selectAll();
        rouses = newRouseService.checkRoot(rouses,session);
        String userId = (String) session.getAttribute("userid");
        LbbUser lbbUser = lbbUserMapper.getByUserId(userId);
      //  rouses = newRouseService.checkRoot(rouses,session);
        model.addAttribute("item", rouses);
        if(MyConfig.getEnv()==1){
            if(lbbUser.getUsername().equals("fangjf")){
                model.addAttribute("fishMark",1);
            }else {
                model.addAttribute("fishMark", 0);
            }
        }else{
            model.addAttribute("fishMark",0);
        }
        return "/taskworthrecord/list";
    }

    @Login
    @GetMapping("/add")
    @DataSource("commonDB")
    public String add(Integer id, Model model) {
        TaskWorthRecord vo;
        if (id != null) {
            vo = baseService.selectById(id);
        } else {
            vo = new TaskWorthRecord();
        }
        vo.setAppid(MyConfig.getEnv());
        model.addAttribute("item", vo);
        List<TaskRouse> rouses = newRouseService.selectAll();
        //  rouses = newRouseService.checkRoot(rouses,session);
        model.addAttribute("ite", rouses);
        return "/taskworthrecord/edit";
    }


    @Login
    @GetMapping("/editPage")
    @DataSource("commonDB")
    public String editPage(Integer id, Model model) {
        TaskWorthRecord vo;
        if (id != null) {
            vo = baseService.selectById(id);
        } else {
            vo = new TaskWorthRecord();
        }
        vo.setAppid(MyConfig.getEnv());
        model.addAttribute("item", vo);
        List<TaskRouse> rouses = newRouseService.selectAll();
        //  rouses = newRouseService.checkRoot(rouses,session);
        model.addAttribute("ite", rouses);
        return "/taskworthrecord/editPage";
    }

    @Login
    @PostMapping("/edit")
    @ResponseBody
    public JsonData edit(TaskWorthRecord vo) {

        List<TaskWorthRecord> records = new ArrayList<>();
        records.add(vo);
        List<TaskWorthRecord> recordList = baseService.calculationRecord(records);
        baseService.delete(vo.getId());
        baseService.deleteByRecordId(vo.getId());
        baseService.insertList(recordList);
//        vo = baseService.checkData(vo);
//
//        if (vo.getId() != null) {
//            baseService.update(vo);
//        } else {
//            vo.setCreateTime(LocalDate.now());
//            if(baseService.checkExit(vo)){
//                return Callback.success("success", "当前记录日期对应的数据源任务价值已存在");
//            }
//            baseService.insert(vo);
//        }
        return Callback.success("success", "保存成功");
    }


    @Login
    @PostMapping("/saveEdit")
    @ResponseBody
    public JsonData saveEdit(String records) {
        List<TaskWorthRecord> recordList = JSON.parseArray(records, TaskWorthRecord.class);
        recordList = baseService.calculationRecord(recordList);
        baseService.insertList(recordList);
        return Callback.success("success", "保存成功");
    }


    /**
     * @param page
     * @param limit
     * @return
     */
    @PostMapping("/page")
    @ResponseBody
    @Login
    @DataSource("commonDB")
    public HashMap newlist(String sdkKey, Long page, Integer limit, Integer appId,String appStore,Integer star,Integer end,HttpSession session) {
        HashMap map = new HashMap(1);
        List<String> sList = null;
//        TaskWorthRecordExample example = new TaskWorthRecordExample();
//        TaskWorthRecordExample.Criteria c = example.createCriteria();
//        example.setOffset((page - 1) * limit);
//        example.setLimit(limit);
//        example.setOrderByClause("time desc");
//        if (!TextUtil.isEmpty(appId)) {
//            c.andAppidEqualTo(appId);
//        }else{
//            c.andAppidEqualTo(MyConfig.getEnv());
//        }
//        if (!TextUtil.isEmpty(sdkKey)) {
//            c.andSdkKeyEqualTo(sdkKey);
//        } else {
//            sdkKey = null;
//        }
//        if(!TextUtil.isEmpty(appStore)){
//            c.andAppStoreEqualTo(appStore);
//        }
//        if(!TextUtil.isEmpty(star)&&!TextUtil.isEmpty(end)){
//            c.andTimeBetween(star,end);
//        }
//        map.put("count", baseService.countByExample(example));
//        map.put("code", 0);
//        List<TaskWorthRecord> masters = baseService.selectByExample(example);
//        map.put("data", masters);
//        return map;

        List<String> appStores;
        if (TextUtil.isEmpty(appId)) {
            appId=MyConfig.getEnv();
        }
        if (TextUtil.isEmpty(sdkKey)) {
            sdkKey = null;
        }
        if(!TextUtil.isEmpty(appStore)){
            appStores = JSON.parseArray(appStore,String.class);
        }else{
            appStores=null;
        }
        if(TextUtil.isEmpty(star,end)){
            star=null;
            end=null;
        }
        if(newRouseService.isRoot(session)){
            sList = sdkList;
        }
        if(!TextUtil.isEmpty(appStore)&&appStore.equals("[\"all\"]")){
           // List<Integer> timeList =  baseService.selectTime((page - 1) * limit,limit,appId,sdkKey,star,end,sList);
            map.put("count", baseService.countAll(appId,sdkKey,star,end,sList));
            map.put("code", 0);
//            if (timeList != null) {
//                star = timeList.get(timeList.size() - 1);
//                end = timeList.get(0);
//            }
            List<TaskWorthRecord> records = baseService.sumDataGroubySdk((page - 1) * limit,limit,appId,sdkKey,star,end,sList);
            records = baseService.sumAllAppStoreData(records);
            map.put("data", records);
            return map;
        }
        List<TaskWorthRecord> list = baseService.selectList((page - 1) * limit,limit,appStores,appId,sdkKey,star,end,sList);
        map.put("count", baseService.countList(appStores,appId,sdkKey,star,end,sList));
        map.put("code", 0);
        map.put("data", list);
        return map;
    }


    @Login
    @PostMapping("/delete")
    @ResponseBody
    @DataSource("commonDB")
    public JsonData delete(Integer id) {
        baseService.deleteById(id);
        return Callback.success("success", "删除成功");
    }


}
